package com.example.libcommen

import android.app.Application
import java.lang.Exception
import java.lang.reflect.InvocationTargetException

/**
 *  伴生对象实现获取application
 */
class AppGlobals {

    companion object {
        private var sApplication: Application? = null
        val application: Application
            get() {
                if (sApplication == null) {
                    try {
                        val method = Class.forName("android.app.ActivityThread").getDeclaredMethod("currentApplication")
                        sApplication = method.invoke(null) as Application
                    } catch (e: ClassNotFoundException) {
                        e.printStackTrace();
                    } catch (e: NoSuchMethodException) {
                        e.printStackTrace();
                    } catch (e: IllegalAccessException) {
                        e.printStackTrace();
                    } catch (e: IllegalArgumentException) {
                        e.printStackTrace();
                    } catch (e: InvocationTargetException) {
                        e.printStackTrace();
                    } catch (e: Exception) {
                        e.printStackTrace();
                    }
                }
                return sApplication!!
            }
    }

}

/**
 * 静态变量的实现获取application
 */
//object AppGlobals {
//
//    private var sApplication: Application? = null
//
//    @JvmStatic
//    val application: Application
//        get() {
//            if (sApplication == null) {
//                try {
//                    val method = Class.forName("android.app.ActivityThread").getDeclaredMethod("currentApplication")
//                    sApplication = method.invoke(null) as Application
//                } catch (e: ClassNotFoundException) {
//                    e.printStackTrace();
//                } catch (e: NoSuchMethodException) {
//                    e.printStackTrace();
//                } catch (e: IllegalAccessException) {
//                    e.printStackTrace();
//                } catch (e: IllegalArgumentException) {
//                    e.printStackTrace();
//                } catch (e: InvocationTargetException) {
//                    e.printStackTrace();
//                } catch (e: Exception) {
//                    e.printStackTrace();
//                }
//            }
//            return sApplication!!
//        }
//}